package com.qiangesoft.security.filter;

import com.qiangesoft.security.handler.CustomAuthenticationFailHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码过滤器
 *
 * @author qiangesoft
 * @date 2024-05-14
 */
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    private CustomAuthenticationFailHandler customAuthenticationFailHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String url = request.getRequestURI();
        // 登录校验验证码
        if ("/login".equals(url) && "POST".equals(request.getMethod())) {
            String captcha = request.getParameter("captcha");
            if (!"1234".equals(captcha)) {
                customAuthenticationFailHandler.onAuthenticationFailure(request, response, new AuthenticationServiceException("验证码错误"));
            }
        }
        filterChain.doFilter(request, response);
    }

}
